package sort.cmp;

/**
 * @Author kaho
 * @create 2020/12/3
 */
public class 归并排序 {

    static int[] leftArr;

    public static void sort(int[] arr) {
        leftArr = new int[arr.length >> 1];
        sort(arr, 0, arr.length);
    }

    public static void sort(int[] arr, int begin, int end) {
        if (end - begin < 2) {
            return;
        }
        int mid = begin + ((end - begin) >> 1);
        sort(arr, begin, mid);
        sort(arr, mid, end);
        merge(arr, begin, mid, end);
    }

    private static void merge(int[] arr, int begin, int mid, int end) {
        int li = 0, le = mid - begin;
        int ri = mid, re = end;
        int a = begin;

        for (int i = 0; i < le; i++) {
            leftArr[i] = arr[i + begin];
        }
        while (li < le) {
            if (ri<re && leftArr[li] > arr[ri]) {
                arr[a++] = arr[ri++];
            } else {
                arr[a++] = leftArr[li++];
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[]{1,4,2,7,8,56,4,3,88,1};
        sort1(arr);
    }

    public static void sort1(int[] arr){
        leftArr = new int[arr.length >> 1];
        divide(arr, 0, arr.length);
    }

    public static void divide(int[] arr, int s, int e){
        if (e-s<2) {
            return;
        }
        int mid = s + (e - s) / 2;
        divide(arr, s, mid);
        divide(arr, mid, e);
        merge1(arr,s, mid, e);
    }

    private static void merge1(int[] arr, int s, int mid, int e) {
        int li = 0, le = mid-s;
        int ri = mid, re = e;
        int ai = s;

        for (int i = 0; i < le; i++) {
            leftArr[i] = arr[i+s];
        }
        while (li<le){
            if (ri<re&&leftArr[li]>arr[ri]){
                arr[ai++] = arr[ri++];
            }else {
                arr[ai++] = leftArr[li++];
            }
        }

    }
}
